package com.hopu.erp.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Security的配置
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    public static final String CONTENT_TYPE = "application/json;charset=UTF-8";

    /**
     * 配置密码加密器
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JdbcTokenRepositoryImpl jdbcTokenRepository;

    /**
     * 配置登录的账号、密码和角色、权限   Authentication 验证  Authorization 授权
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置自定义登录逻辑
        auth.userDetailsService(userDetailsService);
    }

    /**
     * 页面资源的授权
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //对请求进行授权
        http.authorizeRequests()
                .antMatchers("/page/login.html","/swagger-ui.html","/js/**","/css/**","/functions/username").permitAll()  //放行
//                .antMatchers("/page/functions/**","/page/role/**","/page/user/**").hasRole("管理员") //必须有对应角色才能访问
                .anyRequest().authenticated()  //其它的请求需要登录
                .and()
                .formLogin()//登录配置
                .loginPage("/page/login.html") //将登录页面配置为自定义的
                .loginProcessingUrl("/doLogin") //配置默认处理登录的URL
                .successHandler((req,resp,auth) -> {  //进行登录成功后的处理
                    resp.setContentType(CONTENT_TYPE);
                    //获得用户信息
                    Object principal = auth.getPrincipal();
                    //转换为JSON
                    resp.getWriter().print(new ObjectMapper().writeValueAsString(principal));
                    resp.getWriter().close();
                })
                .failureHandler((req,resp,auth) -> {  //进行登录失败的处理
                    resp.setContentType(CONTENT_TYPE);
                    resp.getWriter().print("{\"msg\":\"账号或密码错误\"}");
                    resp.getWriter().close();
                })
                .and()
                .exceptionHandling() //未进行登录请求的处理
                .authenticationEntryPoint((req,resp,auth)->{
                    resp.setContentType(CONTENT_TYPE);
                    resp.getWriter().print("{\"msg\":\"你没有权限访问\"}");
                    resp.getWriter().close();
                })
                .and()
                .logout()//登出配置
                .logoutUrl("/logout")  //登出url
                .logoutSuccessHandler((req,resp,auth) -> {
                    resp.setContentType(CONTENT_TYPE);
                    resp.getWriter().print("{\"msg\":\"注销成功\"}");
                    resp.getWriter().close();
                })
                .and()
                .rememberMe()//配置记住我
                .rememberMeParameter("rememberMe") //配置表单参数名
                .tokenRepository(jdbcTokenRepository) //配置jdbc操作
                .tokenValiditySeconds(24 * 3600) //保存时间
                .and()
                .cors() //跨域配置
                .and()
                .csrf().disable(); //关闭CSRF防御
        //配置http解决iframe不能跳转的问题
        http.headers().frameOptions().sameOrigin().httpStrictTransportSecurity().disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
